package com.hujf.netty.example.server;

import com.hujf.netty.example.handle.SimpleHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author Hujf
 * @title: simpleServer
 * @date 2021/1/28 0028下午 12:31
 * @description: 简单的nettyserver
 */
public class SimpleServer {

    public static void main(String[] args) throws InterruptedException {
        //1.创建bossgroup 和workgroup
        /**
         * 创建了2个线程组
         * 1.boss只处理连接
         * 2.work与客户端业务处理   懂老板和工人的关系了吧
         * 3.线程组 无线循环
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            //netty启动 启动参数
            ServerBootstrap server = new ServerBootstrap();

            //链式编程进行设置
            server.group(bossGroup, workGroup)
                    //设置两个需要的group
                    .channel(NioServerSocketChannel.class)
                    //设置一个通道 NIO的
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //线程队列连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //设置保持活动连接
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        //给pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new SimpleHandler());//得到返回的pipeline
                        }
                    });   //设置处理器

            ChannelFuture cf = server.bind(8889).sync();
            System.out.println(cf + " 服务器准备好了");

            //监听关闭的通道
            cf.channel().closeFuture().sync();

        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
